﻿using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace MyOCR_WPF.TranslateHelper
{
    public class SouGouTranslate:ITranslate
    {
        // 搜狗云中开通对应服务应用的 API Key 建议开通应用的时候多选服务
        private static String clientId;
        // 搜狗云中开通对应服务应用的 Secret Key
        private static String clientSecret;
        public SouGouTranslate()
        {
            clientId = ConfigurationManager.AppSettings["SouGou_Id"];
            clientSecret = ConfigurationManager.AppSettings["SouGou_Key"];
        }

        public string SendContent(string content)
        {
            string authHost = "http://fanyi.sogou.com/reventondc/api/sogouTranslate";

            RestClient restClient = new RestClient(authHost);
            RestRequest restRequest = new RestRequest(Method.POST);

            restRequest.AddParameter("q", content);
            restRequest.AddParameter("from", "auto");
            restRequest.AddParameter("to", "zh-CHS");
            restRequest.AddParameter("pid", clientId);
            restRequest.AddParameter("salt", "011225");
            restRequest.AddParameter("sign", getSign(content));

            try
            {
                var result = restClient.Execute(restRequest);
                var lst = new List<string>();
                dynamic json = JsonConvert.DeserializeObject(result.Content);
                return string.Join("\r\n\r\n    ", json.translation.ToString());
            }
            catch (Exception)
            {
                return "出现了点小问题";
            }
        }

        protected string getSign(string q)
        {
            string sign = string.Format("{0}{1}{2}{3}", clientId, q.Trim(), "011225", clientSecret);
            var md5 = new MD5CryptoServiceProvider();
            var result = Encoding.UTF8.GetBytes(sign);
            var output = md5.ComputeHash(result);

            return BitConverter.ToString(output).Replace("-", "").ToLower();
        }
    }
}
